jsForms.Templates["page.builder"]='<div>Builder'+
	'<div class="control-panel panel-left">'+
	'<component type="common.Select">'+
		'<content into="object">'+
			'<option value="file">File</option>'+
			'<option value="component">Component</option>'+
		'</content>'+
		'<events>'+
			'<key name="onChangeSelect" value="LeftPanelChangeView"/>'+
		'</events>'+
	'</component>'+
	'<component type="common.RemoteFileExplorer" name="rfeFileExplorer">'+
		'<properties>'+
			'<key name="ServerService" value="server/filesystem/action.php"/>'+
		'</properties>'+
		'<events>'+
			'<key name="onItemDoubleClick" value="FileExplorerDoubleClick"/>'+
		'</events>'+
	'</component>'+
	'<component type="common.TreeView" name="tvComponentList">'+
	'</component>'+
	'</div>'+
	'<div class="control-panel panel-middle">'+
	'<component type="common.TabControl" name="edit_items">'+
	'</component>'+
	'</div>'+
	'<div class="control-panel panel-right">'+
	'<component type="common.Button">'+
		'<properties>'+
			'<key name="Text" value="Test"/>'+
		'</properties>'+
		'<events>'+
			'<key name="onClick" value="TestClick"/>'+
		'</events>'+
	'</component>'+
	'<component type="common.Button">'+
		'<properties>'+
			'<key name="Text" value="Parse"/>'+
		'</properties>'+
		'<events>'+
			'<key name="onClick" value="TestParseText"/>'+
		'</events>'+
	'</component>'+
	'<component type="common.Button">'+
		'<properties>'+
			'<key name="Text" value="SyncLoadServer"/>'+
		'</properties>'+
		'<events>'+
			'<key name="onClick" value="TestSyncLoadServer"/>'+
		'</events>'+
	'</component>'+
	'<textarea name="test_text">'+
	'</textarea>'+
	'<div name="test_parse_result"/>'+
	'</div>'+
	'<div name="splash">'+
		'<span name="current_path"/>'+
		'<component type="common.ProgressBar" name="parse_progress" class="progressbar-loading-project">'+
		'</component>'+
	'</div>'+
'</div>';

//project_folder - папка проекта
//project_configuration - настройки проекта
//component_list - список компонентов


// Project configuration
var SampleProjectConfiguration=
{
	name:"Test project", // 
	paths:{ // пути
		ignore:[], //Игнорируемые папки
		css:['css/'], // Таблицы стилей
		images:['images/'], //Картинки
		data:['data/'],// Данные
		pages:[''], // папки где лежат страницы html, php, jsp, aspx ...
		server_side:{
			handlers:['servers/']
		},
		client_side:{
			common:['scripts/engine/','scripts/plugins/','scripts/plugins/ui/','scripts/common/'],
			components:[
				'scripts/pages/',
				'scripts/view/',
				'scripts/view/common/',
				'scripts/view/phonebook/',
				'scripts/view/builder/',
				'scripts/class/',
				'scripts/class/phonebook/',
				'scripts/class/builder/',
				'scripts/class/common/']
		}
	}
};

jsForms.Components["page.builder"]={
	MsgBroker:new MessageBroker(BuilderConfig.Handlers.Push,BuilderConfig.Handlers.PushAuth),
	//Singletone
	_ScanProjectFolder:function(){
		var cfg = this.P.project_configuration;
		if (cfg.paths == undefined || cfg.paths.client_side == undefined || cfg.paths.client_side.components == undefined){
			return;
		}
		var list = cfg.paths.client_side.components;

		var items = [];
		var mc = this;
		this.P.component_list = {};
		var component_list = this.P.component_list;

		function parseFileContent(data){
			if (Error.isError(data)){
				console.error(Error.getErrorMessages(data));
				return;
			}
			var filename = items.shift();
			if (filename){
				var ret = DetectComponent.scan(data);
				if (ret.length > 0){
					//console.log(' -------------- '+filename+' -------------- ');
					//console.log($.toJSON( ret ));
					//component_list
					for(var i = 0 ; i < ret.length ;i++){
						component_list[ret[i].name] = filename;
					}
				}
			}
			if(items.length != 0 ){
				TaskManager.addTask(undefined,loadFileContent);
			}else if (reqCount == 0){
				mc.C.splash.remove();
				TaskManager.addTask(mc,mc.UpdateComponentList);
			}
			mc.C.parse_progress.SetValue(mc.C.parse_progress.GetValue()+1);
		}

		function loadFileContent(){
			var filename = items[0];//.shift();
			FileManager.getFileContent(filename,parseFileContent);
		};
		
		var reqCount = 0;
		function onFileList(json){
			if (Error.isError(json)){
				console.error(Error.getErrorMessages(json));
				reqCount--;
				if (reqCount==0 && items.length >0 ){
					TaskManager.addTask(undefined,loadFileContent);					
				}
				return;
			}
			for (var i = 0 ; i < json.length ; i++){
				var item = json[i];
				if (item.t != 'd'){
					maxValue++;
					items.push(item.p)
				}
			}
			mc.C.parse_progress.SetMax(maxValue);
			reqCount--;
			if (reqCount==0 && items.length >0 ){
				TaskManager.addTask(undefined,loadFileContent);					
			}
		};

		mc.C.parse_progress.SetMax(0);
		var maxValue = 0;
		reqCount = list.length;
		for(var i= 0 ; i < list.length ; i++){
			FileManager.getItems(Utils_Path_Combine(this.P.project_folder,list[i]),'*.js;*.xml',onFileList);
		}
		//
	},
	_LoadProjectConfiguration:function(){
		var mc = this;
		function onLoad(json){
			if (Error.isError(json)){
				console.error(Error.getErrorMessages(json));
				return;
			}
			mc.P.project_configuration = json;
			mc._ScanProjectFolder();
		}
		//$.getJSON(,onLoad);
		onLoad(window.SampleProjectConfiguration);
	},
	Init:function()
	{
		this.MsgBroker.authenticate("admin", "admin");
		this.P.project_folder = URLUtils.GetParameter("path");
		this.C.rfeFileExplorer.SetRoot(this.P.project_folder).P.ServerService = BuilderConfig.Handlers.FileSystem;
		this._LoadProjectConfiguration();
		return jsForms.Components.Component.Init.call(this);
	},
	LeftPanelChangeView:function($select){
		var value = $select.GetValue();
		if (value == "file"){
			this.C.rfeFileExplorer.show();
			this.C.tvComponentList.hide();
		}else{
			this.C.rfeFileExplorer.hide();
			this.C.tvComponentList.show();
		}
	},
	// Двойной клик в дереве файлов
	FileExplorerDoubleClick:function($item){
		if ($item.GetType()!='f'){
			return;
		};
		//Если файл то попытаться открыть
		this.OpenFileForEdit($item.GetName(),$item.GetPath());
	},
	// Открыть файл на редактирование
	OpenFileForEdit:function(name,fullpath){
		var mainControl = this;
		function onload(data){
			if (Error.isError(data)){
				console.error(Error.getErrorMessages(data));
				return;
			}
			var ext =  name.replace(/^.*\./,'');
			var newTab = mainControl.CreateNewTab(name);
			var sourceEditor = jsForms.CreateComponent('builder.SourceEditor');
			var syntax;
			switch(ext){
				case "js":
				syntax = "js";
				break;
				case "html":
				syntax = "html";
				break;
				case "css":
				syntax = "css";
				break;
				default:
				syntax = "text";
				break;
			}
			sourceEditor.P.InitParam={syntax:syntax};
			newTab.AppendContent(sourceEditor);
			sourceEditor.Init().SetSource(data);
		}
		FileManager.getFileContent(fullpath,onload);
	},
	// Создать новый таб
	CreateNewTab:function(title){
		var newTab = jsForms.CreateComponent('common.TabItem');
		newTab.SetTitle(title);
		this.C.edit_items.AppendTab(newTab);
		return newTab.Init();	
	},
	UpdateComponentList:function(){
		var tree = this.C.tvComponentList;
		tree.Clear();
		var list = this.P.component_list;
		var hash = {};
		var nameSplit = /\./;
		//debugger;
		for(var i in list){
			var item = list[i];
			var treeItem = tree;
			var ns = i.split(nameSplit);
			var deepname = undefined;
			for(var ii=0;ii<ns.length;ii++){
				var nsitem = ns[ii];
				if (deepname==undefined){
					deepname = nsitem;
				}else{
					deepname += '.'+nsitem;
				}
			        if (hash[deepname] == undefined){
					var tmp = tree.CreateNode().SetText(nsitem);
					treeItem.AddChild(tmp);
					treeItem = tmp;
					hash[deepname] = tmp;
				}else{
					treeItem = hash[deepname];
				}
			}
			treeItem.SetId(i);
		}
		//var ii = tree.CreateNode();
		//ii.SetText('aaaaa');
		//tree.AddChild(ii);
	},
	TestClick:function(){
		this.UpdateComponentList();
		return;		
		//URLUtils.Test();
		//var iframeSource = '<iframe onload="alert(\'load\');"></iframe>';
		//var $frame = $(iframeSource).appendTo(document.body);
		if (this.P.testCount == undefined){
			this.P.testCount = 0;
		}
		this.P.testCount++;
		var newTab = jsForms.CreateComponent('common.TabItem');
		//var ce = jsForms.CreateComponent('ComponentEditor');
		//ce.SetComponentName(compType);
		//newTab.AppendContent(ce);
		//newTab.SetTitle(compType);
		//newTab._AddComponent(ce);		
	
		var $text = $('<textarea class="codepress">asdf_'+this.P.testCount+'</textarea>');
		newTab.AppendContent($text);
		newTab.SetTitle('Test_'+this.P.testCount);
		
		this.C.edit_items.AppendTab(newTab);
		var sourceEditor = new CodePress($text[0]);
		$text.before(sourceEditor);
		//debugger;
		//sourceEditor.initialize();
		newTab.Init();

	},
	TestSyncLoadServer:function(){
		function onCallback(json){
			console.log('Callback:'+$.toJSON(json));
		};

		$.ajax({
			async:false,
			data:{pause:4},
			dataType:'json',
			type:'GET',
			url:'./server/test/sync.php',
			success:onCallback
		});
		console.log('Return control');
	},
	TestParseText:function(){
		
		//this.C.test_parse_result.text(this.C.test_text.val());
	var mc = this;

	function onload(data){
		var ret = DetectComponent.scan(data);
		if (ret.length != 0)
		{
			mc.C.test_parse_result.text($.toJSON(ret));
		}else{
			mc.C.test_parse_result.text('-- ERROR --');
		}
	}
	$.get('scripts/class/common/listbox.js',onload);
	}
};
